import json
import requests
import os

def upload_filter_regions():
    """
    读取过滤区 GeoJSON 文件并上传每个要素
    """
    try:
        # 获取当前脚本所在目录
        current_dir = os.path.dirname(os.path.abspath(__file__))
        geojson_path = os.path.join(current_dir, 'geojson', 'filterRegion.geojson')
        
        # 读取 GeoJSON 文件
        with open(geojson_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # API 配置
        url = "http://localhost:8080/project-setting/project-filter-region/add"
        headers = {
            "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1dWlkIjoiODgwODI2YzhlZDFlNGM5OGI0MWE3NjAxNTgwNjY2MjIiLCJ1c2VySWQiOjEwOCwiaWF0IjoxNzQyMzgwNjI5fQ.wyiiYKPGh0w8_OoRWpSc3LgoWqqk3H9JyonLFWOM540",
            "Content-Type": "application/json"
        }
        
        # 遍历每个要素并上传
        for feature in data['features']:
            # 构建请求数据
            request_data = {
                "projectName": "fenghuang",
                "algorithmCode": "building",
                "geojson": feature
            }
            
            try:
                # 发送 POST 请求
                response = requests.post(url, json=request_data, headers=headers)
                
                # 打印响应结果
                print(f"上传结果: {response.json()}")
                
            except Exception as e:
                print(f"上传要素时发生错误: {str(e)}")
                continue
        
        print("\n处理完成！")
        
    except Exception as e:
        print(f"程序执行出错: {str(e)}")

if __name__ == '__main__':
    upload_filter_regions()